package com.mixsmart.commonweb.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.mixsmart.commonweb.IWebConstant;
import com.mixsmart.commonweb.bean.TreeProp;
import com.mixsmart.commonweb.bean.entity.TCRoleUrlRes;
import com.mixsmart.commonweb.bean.entity.TCUrlResOpFlag;
import com.mixsmart.commonweb.bean.entity.TCUrlResource;
import com.mixsmart.commonweb.service.IRoleUrlResService;
import com.mixsmart.spellsql.utils.Cnd;
import com.mixsmart.spellsql.utils.Exp;
import com.mixsmart.utils.ArrayUtils;
import com.mixsmart.utils.CollectionUtils;

/**
 * 角色URL资源--服务类
 * @author lmq
 * @version 1.0
 * @since JDK1.6以上
 * <br />
 * 2016年7月22日
 */
@Service
public class RoleUrlResService extends WebMgrService<TCRoleUrlRes> implements IRoleUrlResService {

	@Autowired
	private UrlResOpFlagService urlResOpServ;
	
	@Override
	@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
	public boolean save(String roleId, List<TreeProp> resAuths) {
		boolean is = false;
		if(StringUtils.isNotEmpty(roleId) && CollectionUtils.isNotEmpty(resAuths)) {
			ArrayList<TCRoleUrlRes> list = new ArrayList<TCRoleUrlRes>();
			TCRoleUrlRes roleUrlRes = null;
			Map<String, List<String>> resAuthMap = this.urlResAuthClassify(resAuths);
			
			Set<String> urlResIds = resAuthMap.keySet();
			for(String urlResId : urlResIds) {
				//获取操作权限（按钮）ID；多个值之间用英文逗号“,”分隔
				StringBuilder opAuthIdBuffer = null;
				List<String> authResIds = resAuthMap.get(urlResId);
				if(CollectionUtils.isNotEmpty(authResIds)) {
					opAuthIdBuffer = new StringBuilder();
					String[] ids = new String[authResIds.size()];
					authResIds.toArray(ids);
					List<TCUrlResOpFlag> urlResOpFlags = urlResOpServ.finds(ids);
					if(CollectionUtils.isNotEmpty(urlResOpFlags)) {
						for(TCUrlResOpFlag urlResOpFlag : urlResOpFlags) {
							opAuthIdBuffer.append(urlResOpFlag.getOpFlagId()+IWebConstant.MULTI_VALUE_SPLIT);
							if(StringUtils.isNotEmpty(urlResOpFlag.getPostUrlResId())) {
								roleUrlRes = new TCRoleUrlRes(roleId, urlResOpFlag.getPostUrlResId());
								list.add(roleUrlRes);
							} 
							if(StringUtils.isNotEmpty(urlResOpFlag.getViewUrlResId())) {
								roleUrlRes = new TCRoleUrlRes(roleId, urlResOpFlag.getViewUrlResId());
								list.add(roleUrlRes);
							}
						}
					}//if
				}//if
				roleUrlRes = new TCRoleUrlRes(roleId, urlResId);
				if(null != opAuthIdBuffer)
					roleUrlRes.setOpAuths(opAuthIdBuffer.toString());
				list.add(roleUrlRes);
			}//for
			roleUrlRes = null;
			is = super.save(list);
			list = null;
		} else {
			throw new IllegalArgumentException("参数传递错误");
		}
		return is;
	}

	/**
	 * URL资源、操作权限归类；如：资源ID作为MAP的key；操作权限ID列表作为value
	 * @param resAuths 资源操作权限列表
	 * @return 返回归类后
	 */
	private Map<String, List<String>> urlResAuthClassify(List<TreeProp> resAuths) {
		Map<String, List<String>> resAuthMap = new HashMap<String, List<String>>();
		for(TreeProp treeProp : resAuths) {
			if(IWebConstant.RES_FLAG.equals(treeProp.getFlag())) {
				this.createList(treeProp.getId(), resAuthMap);
			} else if(IWebConstant.AUTH_FLAG.equals(treeProp.getFlag())) {
				this.createList(treeProp.getParentId(), resAuthMap);
				List<String> list = resAuthMap.get(treeProp.getParentId());
				list.add(treeProp.getId());
			}
		}
		return resAuthMap;
	}
	
	/**
	 * 创建列表
	 * @param id
	 * @param resAuthMap
	 */
	private void createList(String id, Map<String, List<String>> resAuthMap) {
		List<String> list = resAuthMap.get(id);
		if(null == list) {
			list = new ArrayList<String>();
			resAuthMap.put(id, list);
		}
	}
	
	@Override
	@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
	public boolean save(String roleId, TCUrlResource urlRes) {
		boolean is = false;
		StringBuilder opAuthIdBuffer = null;
		ArrayList<TCRoleUrlRes> list = new ArrayList<TCRoleUrlRes>();
		TCRoleUrlRes roleUrlRes = new TCRoleUrlRes(roleId, urlRes.getId());
		if(CollectionUtils.isNotEmpty(urlRes.getResOpFlags())) {
			opAuthIdBuffer = new StringBuilder();
			for(TCUrlResOpFlag urlResOpFlag : urlRes.getResOpFlags()) {
				opAuthIdBuffer.append(urlResOpFlag.getOpFlagId()+IWebConstant.MULTI_VALUE_SPLIT);
				if(StringUtils.isNotEmpty(urlResOpFlag.getPostUrlResId())) {
					roleUrlRes = new TCRoleUrlRes(roleId, urlResOpFlag.getPostUrlResId());
					list.add(roleUrlRes);
				} 
				if(StringUtils.isNotEmpty(urlResOpFlag.getViewUrlResId())) {
					roleUrlRes = new TCRoleUrlRes(roleId, urlResOpFlag.getViewUrlResId());
					list.add(roleUrlRes);
				}
			}//for
		}//if
		if(null != opAuthIdBuffer)
			roleUrlRes.setOpAuths(opAuthIdBuffer.toString());
		list.add(roleUrlRes);
		return is;
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
	public boolean update(String roleId, List<TreeProp> treeProps) {
		boolean is = false;
		//删除角色与URL资源的关联关系
		if(super.delete(Cnd.where(Exp.eq("roleId", roleId)))){
			//如果角色与URL资源有关系，则重新保存
			if(CollectionUtils.isNotEmpty(treeProps))
				 this.save(roleId, treeProps);
			treeProps = null;
			is = true;
		}
		return is;
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
	public boolean update(String roleId, TCUrlResource urlRes) {
		boolean is = false;
		//删除角色与URL资源的关联关系
		if(super.delete(Cnd.where(Exp.eq("roleId", roleId)))){
			//如果角色与URL资源有关系，则重新保存
			if(null != urlRes)
				this.save(roleId, urlRes);
			urlRes = null;
			is = true;
		}
		return is;
	}

	@Override
	@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
	public boolean deleteOpFlag(String[] opFlagIds) {
		boolean is = false;
		if(ArrayUtils.isNotEmpty(opFlagIds)) {
			List<TCRoleUrlRes> all = new ArrayList<TCRoleUrlRes>();
			StringBuilder strBuilder = new StringBuilder();
			for(String opFlagId : opFlagIds) {
				List<TCRoleUrlRes> list = super.finds(Cnd.where(Exp.like("opAuths", opFlagId)));
				strBuilder.append(opFlagId+",|");
				if(CollectionUtils.isNotEmpty(list)) {
					all.addAll(list);
				}
			}
			Set<TCRoleUrlRes> sets = new HashSet<TCRoleUrlRes>(all);
			all = null;
			String regex = strBuilder.toString();
			regex = regex.substring(0,regex.length()-1);
			for(TCRoleUrlRes roleUrlRes : sets) {
				roleUrlRes.setOpAuths(roleUrlRes.getOpAuths().replaceAll(regex, ""));
			}
			is = super.update(new ArrayList<TCRoleUrlRes>(sets));
		}
		return is;
	}
	
}
